﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.GridType;
using B.S.BasicData.Api.Read.DTOs;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;

namespace B.S.BasicData.Api.Read.Application.Handler.GridType
{
    public class GetGridTypeHandler : IRequestHandler<GetGridTypeCommand, ApiResult<List<GridTypeDTO>>>
    {
        private readonly IBaseRepository<GridTypeModel> gridTypeRepo;
        private readonly IMapper mapper;

        public GetGridTypeHandler(IBaseRepository<GridTypeModel> gridTypeRepo,IMapper mapper)
        {
            this.gridTypeRepo = gridTypeRepo;
            this.mapper = mapper;
        }

        public async Task<ApiResult<List<GridTypeDTO>>> Handle(GetGridTypeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<GridTypeDTO>> res = new ApiResult<List<GridTypeDTO>>();

            var gridTypes = gridTypeRepo.GetAll().Where(x=>x.IsDeleted==false);

            if (!string.IsNullOrEmpty(request.GridTypeName)) {
                gridTypes = gridTypes.Where(x=>x.GridTypeName.Contains(request.GridTypeName));
            }
            if (!string.IsNullOrEmpty(request.Category))
            {
                gridTypes = gridTypes.Where(x => x.Category==request.Category);
            }

            List<GridTypeModel> models  =   gridTypes.ToList();
            List<GridTypeDTO> dtos = mapper.Map<List<GridTypeDTO>>(models);

            res.Msg = "查询网格类型列表成功!";
            res.Data = dtos;
            res.Code = ApiEnum.Success;
            return res;

        }
    }
}
